var app = {}
var s = {}
app.param = {}
app.token = ""
app.token_time = ""
app.server = "http://z.nightc.com"
app.debug = false
window.onerror = function(errorMessage, scriptURI, lineNumber, columnNumber, errorObj) { 
    alert("filename : "+scriptURI + "\nline : "+lineNumber + "\ncolumn : "+columnNumber + "\nerrorMessage : "+errorMessage)
}
app.init = function(){
	document.addEventListener('deviceready', app.Init, false);
}
app.Init = function() {
	document.addEventListener('backbutton', app.hide, false);
	s.init()
	s.list(function(data) {
		app.param = data
		app.checkLogin()
		app.run()
	})
}
app.hide = function(){
	//navigator.app.exitApp();
	navigator.Backbutton.goHome();
}
app.ListenMessage = function(){
	var data = {
		user:app.user_name,
		token:app.token,
		token_time:app.token_time,
		lasttime:app.getParam("lastMessageTime")
	}
	//alert(app.getParam("lastMessageTime"))
	s.set("lastMessageTime", Math.round(new Date().getTime()/1000))
	$.ajax({
		url:app.server+"/message/get",
		data:data,
		dataType:"json",
		type:"post",
		success:function(data,status,xhr){
			if (data.code == "0") {
				var time = 0
				for(var i in data.list) {
					cordova.plugins.notification.local.schedule({
					    id: i,
					    title: "TA z 你了",
					    text: "",
					    data: { meetingId:"#123FG8" }
					})
					time = data.list[i].Vibration_long
				}
				navigator.vibrate(Number(time)*1000)
			}
		}
	})
	setTimeout("app.ListenMessage()",5000)
}
app.checkLogin = function(){
	app.token = app.getParam("token")
	app.token_time = app.getParam("token_time")
	app.user_name = app.getParam("user_name")
	if (app.debug) {
		alert("token : "+app.token+"\ntoken_time : "+app.token_time+"\nusername : "+app.user_name)
	};
	if (shouldCheckLogin) {
		if (app.token == "" || app.token == null) {
			window.location.href = "index.html"
		}
	}
	if (page == "index" || page == "login" || page == "regist") {
		if (app.token == "" || app.token_time == "" || app.user_name == "") {
			return
		}
		var data = {
			user:app.user_name,
			token:app.token,
			token_time:app.token_time
		}
		$.ajax({
			url:app.server+"/user/autologin",
			data:data,
			dataType:"json",
			type:"post",
			success:function(data,status,xhr){
				if (data.code == "0") {
					app.updateToken(xhr, function(){
						window.location.href="content.html"
					})
				}
			}
		})
	}
	if (page == "content" || page == "set") {
		if (app.lastMessageTime == null || app.lastMessageTime == 0) {
			s.set("lastMessageTime", Math.round(new Date().getTime()/1000))
		}
		app.ListenMessage()
	}
}
app.updateToken = function(xhr, callback) {
	var t = xhr.getResponseHeader("Custom-Header")
	if (t != "" && t != null) {
		var tokenArr = t.split(":")
		if (tokenArr.length == 2) {
			app.token = tokenArr[0]
			app.token_time = tokenArr[1]
			if (app.token != "" && app.token_time != "") {
				s.set("token", app.token)
				if (typeof callback == "function") {
					callback()
				}	
			}
		}
	} else {
		if (typeof callback == "function") {
			callback()
		}
	}
}
app.getParam = function(key) {
	for(var i in app.param) {
		if(app.param[i].key == key){
			return app.param[i].val
		}
	}
	return ""
}
app.setParam = function(key, val){
	for(var i in app.param) {
		if(app.param[i].key == key){
			app.param[i].val = val
			return
		}
	}
	app.param.push({
		key:key,
		val:val
	})
}
app.loginOut = function(){
	s.db.transaction(function(tx){
		tx.executeSql("DELETE FROM "+s.table, [],function(){
			window.location.href = "index.html"
		})
	})
}
app.getCp = function(callback){
	var data = {
		user:app.user_name,
		token:app.token,
		token_time:app.token_time
	}
	$.ajax({
		url:app.server+"/cp/get",
		data:data,
		dataType:"json",
		type:"post",
		success:function(data,status,xhr){
			if (data.code == "0") {
				app.updateToken(xhr)
				s.set("cp_name", data.cp_name)
				s.set("cp_id", data.cp_id)
				if (typeof callback == "function") {
					callback(data.cp_name, data.cp_id)
				}
			}
		}
	})
}
s.init = function () {
	s.db = openDatabase('z', '1.0', 'z-app', 4 * 1024);
	s.table = "Z"
	s.db.transaction(function (tx) { 
		tx.executeSql('CREATE TABLE IF NOT EXISTS '+ s.table +' (key,val)');
	});
}
s.set = function(key, val, callback) {
	s.has(key, function(key, b){
		if (b) {
			s.db.transaction(function(tx){
				tx.executeSql('UPDATE '+ s.table +' SET val=? WHERE key=?', [val, key],function(){
					if (typeof callback == "function") {
						callback()
					}
				})
			})
		} else {
			s.db.transaction(function(tx){
				tx.executeSql('INSERT INTO '+ s.table +' (key, val) VALUES (?, ?)', [key, val],function(){
					if (typeof callback == "function") {
						callback()
					}
				})
			})
		}
	})
	app.setParam(key, val)
}
s.has = function(key, callback) {
	s.db.transaction(function (tx) {
		tx.executeSql('SELECT * FROM '+ s.table +' WHERE key=?', [key], function(tx, results){
			len = results.rows.length
			if (len > 0) {
				callback(key, true)
			} else {
				callback(key, false)
			}
		});
	})
}
s.get = function(key, callback){
	s.has(key, function(key, b){
		if (b == false) {
			callback("")
		}
		s.db.transaction(function (tx) {
			tx.executeSql('SELECT * FROM Z WHERE key=?', [key], function(tx, results){ 
				for (i = 0; i < results.rows.length; i++){
					val = results.rows.item(i).val
				}
				callback(val)
			})
		})
	})
}
s.list = function(callback){
	s.db.transaction(function (tx) {
		tx.executeSql('SELECT * FROM Z', [], function(tx, results){
			var list = []
			for (i=0; i < results.rows.length; i++){
				var item = {}
				item.val = results.rows.item(i).val
				item.key = results.rows.item(i).key
				list.push(item)
			}
			callback(list)
		})
	})
}
app.Init()